/*****************************************************
 * Mp3Player BeagleBoard                             *
 * Introduccion a Sistemas Embebidos                 *
 *****************************************************
 * Cristian Brenes Quiros                            *
 * Alejandro Morales Araya                           *
 * Pedro Rojas Barrett                               *
 *****************************************************
 * Pipe Servidor                                     *
 * Envia un archivo mp3 por medio de stream para que *
 * dispositivos en red puedan reproducirlo           *
 *****************************************************/



#include <gst/gst.h>
#include <glib.h>

GMainLoop *loop;

GstElement *pipeline, *source, *decoder, *conv, *resample, *mula, *mupay, *sink;

int servidor (char *argv[])
{
  int   argc = 1;;


  /* Inicializacion */
  gst_init (&argc, &argv);

  loop = g_main_loop_new (NULL, FALSE);

  /* Se crean los elementos pertenecientes al pipeline */
  pipeline = gst_pipeline_new ("audio-player");
  source   = gst_element_factory_make ("filesrc",       "file-source");
  decoder  = gst_element_factory_make ("mad",     "mp3-decoder");
  conv     = gst_element_factory_make ("audioconvert",  "converter");
  resample = gst_element_factory_make ("audioresample", "a");
  mula     = gst_element_factory_make ("mulawenc", "aa");
  mupay    = gst_element_factory_make ("rtppcmupay", "aaa");
  sink     = gst_element_factory_make ("udpsink", "sinker");
  g_object_set( sink, "host", "224.1.1.1", "port", 3000, NULL );

  if (!pipeline || !source || !decoder || !conv || !resample || !mula || !mupay || !sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }

  /* Se agrega el path del archivo a reproducir */
  g_object_set (G_OBJECT (source), "location", argv[0], NULL);

  /*Se agrega el resto de elementos para el pipeline*/
  gst_bin_add_many (GST_BIN (pipeline), source, decoder, conv,
        resample, mula, mupay, sink, NULL);

  /* se unen los elementos */
  gst_element_link_many (source, decoder, conv, resample, mula, mupay, sink, NULL);

  /*Se muestra que un mensaje para saber que se esta enviando la cancion*/
  g_print ("Enviando: %s\n", argv[0]);
  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  g_print ("Corriendo...\n");
  g_main_loop_run (loop);

  pararS();

  return 0;
}

void pararS(){

g_print ("Returned, stopping playback\n");
gst_element_set_state (pipeline, GST_STATE_NULL);

g_print ("Deleting pipeline\n");
gst_object_unref (GST_OBJECT (pipeline));
g_main_loop_unref (loop);
}
